package com.nian.message.rocketmq.producer;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 用途：
 * 开发：zhangmj
 * 日期：2020/4/6 0006 20:53
 */
@Service
public class RocketMQProducerImpl implements IRocketMQProducer{

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public SendResult send(String topic, String tag, String body) {
        Message<String> message = MessageBuilder.withPayload(body).build();
        String destination = StringUtils.isNotEmpty(tag)? topic + ":" + tag : topic;
        return rocketMQTemplate.syncSend(destination, message);
    }

    @Override
    public TransactionSendResult sendMessageInTransaction(String topic, String tag, String body)  {
        Message<String> message = MessageBuilder.withPayload(body).setHeader(RocketMQHeaders.TRANSACTION_ID,UUID.randomUUID()).build();
        return rocketMQTemplate.sendMessageInTransaction(topic, message, null);
    }
}
